package com.leetcode.basic.synchronize;

import org.junit.Test;

/**
 * 死锁
 */
public class DeadLock {

	@Test
	public void test() throws InterruptedException {
		A      a    = new A();
		B      b    = new B();
		Object lock = new Object();

		new Thread(() -> {
			synchronized (a) {
				System.out.println("线程1 获得锁a");
				sleep(5);

				synchronized (b) {
					System.out.println("线程1 获得锁b");

					synchronized (lock) {
						lock.notifyAll();
					}
				}
			}
		}).start();
		new Thread(() -> {
			synchronized (b) {
				System.out.println("线程2 获得锁b");
				sleep(5);

				synchronized (a) {
					System.out.println("线程2 获得锁a");

					synchronized (lock) {
						lock.notifyAll();
					}
				}
			}
		}).start();

		synchronized (lock) {
			lock.wait();
			System.out.println("awake up");
		}
	}

	private class A {
		String name = "A";
	}

	private class B {
		String name = "B";
	}

	private void sleep(long time) {
		try {
			Thread.sleep(time);
		} catch (InterruptedException e) {
			e.printStackTrace();
		}
	}
}
